package com.jnzc.ocr.common.utils;

import com.google.common.collect.Maps;
import com.jnzc.ocr.common.error.BusinessException;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/22
 */
public class TemplateUtils {

    private TemplateUtils(){}

    /**
     * 生成内容
     *   模板中的参数名称为${user}
     *   模板参数的key对应上面的参数名称
     * @param tempContent 模板内容
     * @param tempParam 模板参数
     * @return
     * @author zhangcm 2016-10-26 16:26:18
     */
    public static String createContent(String tempContent, Map<String, Object> tempParam){
        ValidateUtils.notEmpty(tempContent, "模板内容");
        tempParam = null == tempParam ? Maps.newHashMap() : tempParam;
        String content = tempContent;
        for(String key : tempParam.keySet()) {
            Object value = tempParam.get(key);
            String regex = "\\$\\{" + transChar(key) + "\\}";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            content = matcher.replaceAll(null == value ? "" : value.toString());
        }
        String regex = "\\$\\{.*?\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        if(matcher.find()){
            throw new BusinessException("缺少" + matcher.group() + "参数");
        }
        return content;
    }

    /**
     * 正则转义
     * @author zhangcm 2016-10-26 17:05:12
     */
    private static String transChar(String source){
        String target = source;
        if(StringUtils.isBlank(target)){
            return target;
        }
        target = target.replace(".", "\\.");
        return target;
    }
}
